#encoding:utf-8
import urllib2
import base64
import hashlib
import hmac
import time
import mimetools
#贴图库Token类
#Author jtu唐
#QQ 	461881920
#邮箱	jtutang@163.com
#@param accesskey 官网开放平台可查询
#@param secretkey 官网开放平台可查询
class ttk_token():
	def __init__(self,accesskey,secretkey):
		self.accesskey = accesskey
		self.secretkey = secretkey

	def create_token(self,param):
		base64param = base64.b64encode(param)
		base64param_encode = base64.b64encode(hmac.new(self.secretkey,base64param,digestmod=hashlib.sha1).digest())
		base64param_encode = base64param_encode.replace("+","-").replace("/","_")
		return self.accesskey + ":" +base64param_encode + ":" + base64param

#贴图库客户端类
#重点写了python版上传文件
#其余功能比较简单,模拟POST请求即可
class ttk_client():
	upload_host = "http://up.tietuku.com/"
	host = "http://api.tietuku.com/v1/"
	def __init__(self,accesskey,secretkey):
		self.token = ttk_token(accesskey,secretkey)

	#上传文件接口
	#@param aid 相册ID
	#@param fn  上传文件路径
	def upload_file(self,aid,fn):
		deadline = str(60 + int(time.time()))
		data = open(fn,"rb").read()
		boundry = mimetools.choose_boundary()
		param = '{"deadline":"%s","aid":"%s"}' % (deadline,aid)
		token = self.token.create_token(param)
		url = self.upload_host
		request = urllib2.Request(url)
		body = "--%s\r\n" % boundry
		body += 'Content-Disposition: file; name="file"; filename="%s"\r\n' % fn
		body += '\r\n'
		body += '%s\r\n' % data
		body += '--%s\r\n' % boundry
		body += 'Content-Disposition: form-data; name="Token"\r\n'
		body += '\r\n'
		body += '%s\r\n' % token
		body += '--%s--\r\n' % boundry 
		request.add_header('Content-type', 'multipart/form-data; boundary=%s' % boundry)
		request.add_header("User-Agent","Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36")
		request.add_header('Content-length', len(body))
		request.add_data(body)
		response = urllib2.urlopen(request)
		return response.read()

	def getRandRec(self,createToken=False):
		url = self.host + "List/";
		deadline = str(60 + int(time.time()))
		param = '{"deadline":"%s","action":"getrandrec"}' % deadline
		token = self.token.create_token(param)
		if createToken:
			return token
		response = urllib2.urlopen(url,"Token="+token)
		return response.read()

	def getRandRecByCid(self,cid,createToken=False):
		url = self.host + "List/";
		deadline = str(60 + int(time.time()))
		param = '{"deadline":"%s","action":"getrandrec","cid":"%s"}' % (deadline,cid)
		token = self.token.create_token(param)
		if createToken:
			return token
		response = urllib2.urlopen(url,"Token="+token)
		return response.read()